package com.projecthost.wizaz;

import java.util.ArrayList;
import java.util.List;

import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlListItem;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlUnorderedList;
import com.projecthost.util.HtmlParser;
import com.projecthost.wizaz.model.ProductBase;
import com.projecthost.wizaz.model.Review;

public class WizazReviewCrawler extends WizazCrawlerBase {

    public WizazReviewCrawler(HtmlParser htmlParser, String mainWizazUrl) {
        super(htmlParser, mainWizazUrl);
    }

    public List<Review> getReviews(int productId) {
        return getReviews(productId, 1, true);
    }

    public List<Review> getReviews(int productId, int pageCount) {
        return getReviews(productId, pageCount, false);
    }

    private List<Review> getReviews(int productId, Integer pageCount, boolean withFollowingPages) {
        String productUrl = ProductBase.getProductUrl(productId, pageCount);
        HtmlPage productPage = htmlParser.getHtmlPageFromUrl(mainWizazUrl + productUrl, false);
        List<Review> reviews = new ArrayList<Review>();
        @SuppressWarnings("unchecked")
        List<HtmlUnorderedList> reviewDivs = (List<HtmlUnorderedList>) productPage.getByXPath("//ul[@class='revcontent']");
        for (HtmlUnorderedList reviewDiv : reviewDivs) {
            HtmlUnorderedList starsElement = (HtmlUnorderedList) reviewDiv.getByXPath(".//li[@class='head']//ul").get(0);
            float starsValue = getStarsValue(starsElement);
            String reviewSummary = ((HtmlListItem) reviewDiv.getByXPath(".//li[@class='summary']").get(0)).getTextContent();
            HtmlListItem reviewFull = (HtmlListItem) reviewDiv.getElementsByAttribute("li", "class", "desc").get(0);
            String reviewUrl = ((HtmlAnchor) reviewDiv.getByXPath("../..//li[@class='url']/a").get(0)).getHrefAttribute();
            int indexOfReviewId = reviewUrl.indexOf("recenzja=");
            Integer reviewId = Integer.valueOf(reviewUrl.substring(indexOfReviewId + "recenzja=".length()));
            reviews.add(new Review(productId, reviewId, starsValue, reviewSummary, reviewFull.getTextContent().trim()));
        }

        if (withFollowingPages) {
            String nextPageUrl = getNextPageUrl(productPage);
            if (nextPageUrl != null) {
                reviews.addAll(getReviews(productId, pageCount + 25, withFollowingPages));
            }
        }
        return reviews;
    }

}
